/*
 * COPYRIGHT. ShenZhen JiMi Technology Co., Ltd. 2017.
 * ALL RIGHTS RESERVED.
 *
 * No part of this publication may be reproduced, stored in a retrieval system, or transmitted,
 * on any form or by any means, electronic, mechanical, photocopying, recording, 
 * or otherwise, without the prior written permission of ShenZhen JiMi Network Technology Co., Ltd.
 *
 * Amendment History:
 * 
 * Date                   By              Description
 * -------------------    -----------     -------------------------------------------
 * 2017年6月28日    li.shangzhi         Create the class
 * http://www.jimilab.com/
 */

package com.jimi.gateway.filter.smarthome.pre;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.jimi.exception.ErrorCode;
import com.jimi.gateway.utils.Constants;
import com.jimi.gateway.utils.ResultModel;
import com.jimi.gateway.utils.ValidatorUtils;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

/**
 * @FileName ShParamFilter.java
 * @Description: SmartHome项目通用参数校验过滤器
 *
 * @Date 2017年6月28日 上午11:14:34
 * @author li.shangzhi
 * @version 1.0
 */
public class ShParamFilter extends ZuulFilter {

	private static final int FILTER_ORDER = 6;

	private final Logger logger = LoggerFactory.getLogger(ShParamFilter.class);

	@Override
	public boolean shouldFilter() {
		RequestContext ctx = RequestContext.getCurrentContext();
		String routeId = String.valueOf(ctx.get("proxy"));
		return Constants.SMARTHOME_NAMESPACE.equals(routeId);
	}

	@Override
	public Object run() {
		RequestContext ctx = RequestContext.getCurrentContext();
		ctx.getResponse().setCharacterEncoding("UTF-8");
		HttpServletRequest request = ctx.getRequest();
		logger.info("{} ShParamFilter request to {}", request.getMethod(), request.getRequestURL().toString());

		Map<String, String[]> paramsMap = request.getParameterMap();
		logger.info("请求的参数内容：{}", JSONObject.toJSONString(paramsMap));
		String[] values = paramsMap.get(Constants.METHOD);
		if (!ValidatorUtils.checkMethod(ctx, values)) {
			ctx.setSendZuulResponse(false);// 过滤该请求，不对其进行路由
			ctx.setResponseStatusCode(200);// 返回错误码
//			ctx.setResponseBody(JSONObject.toJSONString(new ResultModel(ErrorCode.PARAM_ERROR)));
			ctx.set(Constants.IS_NEXT_FILTER, false);// 后续的过滤器是否继续执行
			return null;
		}
		ctx.set(Constants.IS_NEXT_FILTER, true);
		return null;
	}

	@Override
	public String filterType() {
		return Constants.PRE_FILTER;
	}

	@Override
	public int filterOrder() {
		return FILTER_ORDER;
	}
}
